using System.Collections.Concurrent;
using System.Reflection;
using Org.Apache.Rocketmq;
using Vin.Extension.RocketMQ.Attributes;
using Vin.Extension.RocketMQ.Models;
using Vin.Extension.RocketMQ.Options;
using Vin.Tool.AspNetCore.Service;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Attributes;
using Vin.Tool.Enums;

namespace Vin.Extension.RocketMQ.Service;

[Service(Lifetime = Lifetime.Singleton)]
public class ProducerFactory : VinBaseService
{
    private readonly ConcurrentDictionary<Type, VinProducer> _producers = new();
    private RocketMqOption Option => VinApp.GetConfig<RocketMqOption>();

    public async Task<T> GetProducer<T>() where T : VinProducer, new()
    {
        var type = typeof(T);
        if (_producers.TryGetValue(type, out var p))
        {
            return (T)p;
        }

        var attribute = type.GetCustomAttribute<ProducerAttribute>();
        if (attribute == null)
        {
            throw new Exception("需要 使用ProducerAttribute 特性设置信息");
        }

        var producer = new T();
        await producer.Init(Option.ClientConfig, attribute.Topics.ToList(), attribute.MaxAttempts);
        _producers.TryAdd(type, producer);
        return producer;
    }
}